import IntegrationTable, {
	IntegrationTableProps,
	OperatingItem,
} from "@/components/IntegrationTable";
import { ProColumns } from "@ant-design/pro-table";
import React, { useEffect, useState, useRef } from "react";
import { DynamicFormItem } from "@/components/DynamicForm";
import { Image, Radio, Popconfirm, message, Tag, Button, Card } from "antd";
import { PaperClipOutlined } from "@ant-design/icons";
import { arrayToObject, getArray, getString } from "phinney-toolkit";
import copy from "copy-to-clipboard";
import { updateStatus } from "./service";
import Item from "antd/lib/list/Item";
// @page 商家
const HotUpdate: React.FC<any> = () => {
	// 组件是否已经卸载
	let isUnMounted = false;
	const actionRef = useRef<any>();
	// 状态列表
	const updateModelList = [
		{ label: "IOS", value: "ios" },
		{ label: "Android", value: "android" },
	];

	const debugList = [
		{ label: "排除", value: "0", msg: "DEBUG版本无法收到此更新包" },
		{ label: "包含", value: "1", msg: "DEBUG版本可以收到此更新包" },
		{
			label: "仅DEBUG",
			value: "2",
			msg: "只有DEBUG版本可以收到此更新包(一般用于测试)。",
		},
	];

	const enabledStatue = [
		{
			label: "暂停",
			value: "0",
			msg: "暂停更新，用户收不到此更新，已更新的用户不影响。",
		},
		{
			label: "启用",
			value: "1",
			msg: "开启更新，所有用户都会收到此更新。",
		},
		{
			label: "撤回",
			value: "2",
			msg: "回滚更新，用户收不到此更新，已更新的用户将撤回此更新。",
		},
	];

	const udateType = [
		{ label: "自动触发", value: "0", msg: "自动触发，APP自动检测更新。" },
		{
			label: "客户端触发",
			value: "1",
			msg: "仅客户触发，通过执行方法 seui.checkUpdate() 触发更新。",
		},
	];

	const updateFinishRestart = [
		{
			label: "静默",
			value: "0",
			msg: "更新完后没有任何提示，更新内容一般在用户下次使用app时生效。",
		},
		{
			label: "自动重启",
			value: "1",
			msg: "更新完所有包后app自动重启，更新内容即刻生效。",
		},
		{
			label: "提示重启",
			value: "2",
			msg: "更新完此包后提示设置内容，根据用户自己选择。",
		},
	];

	const updateFinishCache = [
		{
			label: "保留缓存",
			value: "0",
			msg: "更新完后没有任何提示，更新内容一般在用户下次使用app时生效。",
		},
		{
			label: "清除缓存",
			value: "1",
			msg: "更新完所有包后app自动重启，更新内容即刻生效。",
		},
	];

	const handleClick = [
		{
			label: "静默",
			value: "0",
		},
		{
			label: "重启",
			value: "1",
		},
	];

	/**
	 * 更新
	 *
	 * @param values
	 *
	 */
	const hadnleUpdateStatus = async (values: any, status: any) => {
		console.log(values);
		try {
			const res = await updateStatus({ id: values, status });
			if (res?.code === 200) {
				message.success(res.msg || "");
				actionRef.current?.reload();
			} else {
				message.error(res.msg || "");
			}
			return true;
		} catch (error) {
			message.error("操作失败请重试！");
			return false;
		}
	};
	// 表格项
	const columns: ProColumns[] = [
		{
			title: "日期",
			dataIndex: "time",
			valueType: "dateRange",
			hideInTable: true,
			search: {
				transform: (value: any) => ({
					startTime: value[0],
					endTime: value[1],
				}),
			},
		},

		{
			title: "更新名称",
			dataIndex: "versionName",
			search: false,
		},
		{
			title: "适合平台",
			dataIndex: "platform",
			search: false,
		},
		{
			title: "DEBUG版本",
			dataIndex: "debug",
			search: false,
			render: (_, record: any) => {
				return (
					<Tag color="blue">
						{["排除DEBUG", "包含DEBUG", "仅DEBUG"][record?.status || 2]}
					</Tag>
				);
			},
		},
		{
			title: "更新模式",
			dataIndex: "updateMode",
			search: false,
			render: (_, record: any) => {
				return record?.updateMode == 0 ? (
					<Tag color="blue">自动触发</Tag>
				) : (
					<Tag color="blue">客户端触发</Tag>
				);
			},
		},
		{
			title: "重启模式",
			dataIndex: "reboot",
			search: false,
			render: (_, record: any) => {
				return record?.reboot == 0 ? (
					<Tag color="blue">静默</Tag>
				) : record?.reboot == 1 ? (
					<Tag color="blue">自动重启</Tag>
				) : (
					<Card title="提示重启">
						<p>{record.rebootTitle}</p>
						<p>{record.rebootMessage}</p>
						<p>
							确认按钮行为:{" "}
							<Tag color="blue">
								{" "}
								{record.rebootConfirmReboot == 0 ? "静默" : "重启"}{" "}
							</Tag>{" "}
						</p>
					</Card>
				);
			},
		},
		{
			title: "缓存处理",
			dataIndex: "clearCache",
			search: false,
			render: (_, record: any) => {
				return record?.clearCache === 0 ? (
					<Tag color="blue">保留缓存</Tag>
				) : (
					<Tag color="blue">清除缓存</Tag>
				);
			},
		},
		{
			title: "启用状态",
			dataIndex: "valid",
			search: false,
			render: (_, record: any) => {
				return record?.valid == 0 ? (
					<Tag color="blue">停止</Tag>
				) : record?.valid == 1 ? (
					<Tag color="blue">启用</Tag>
				) : (
					<Tag color="blue">撤回</Tag>
				);
			},
		},
		// {
		// 	title: "版本号",
		// 	dataIndex: "version",
		// 	search: false,
		// 	render: (_, record: any) => {
		// 		return (
		// 			<Tag icon={<PaperClipOutlined />} color="blue">
		// 				{record.version}
		// 			</Tag>
		// 		);
		// 	},
		// },
		{
			title: "状态",
			dataIndex: "status",
			search: false,
			render: (_, record: any) => {
				return record?.status == 1 ? (
					<div>
						<Popconfirm
							title="确定禁用吗?"
							onConfirm={() => {
								hadnleUpdateStatus(record.id, 2);
							}}
							okText="确定"
							cancelText="取消"
						>
							<Button type="primary" danger size="small">
								禁用
							</Button>
						</Popconfirm>
					</div>
				) : record?.status == 2 ? (
					<div>
						<Popconfirm
							title="确定启用吗?"
							onConfirm={() => {
								hadnleUpdateStatus(record.id, 1);
							}}
							okText="确定"
							cancelText="取消"
						>
							<Button type="primary" size="small">
								启用
							</Button>
						</Popconfirm>
					</div>
				) : (
					<div>
						{" "}
						<Tag color="red">已删除</Tag>
					</div>
				);
			},
		},
	];

	const getFormItems = (vm: any, isEdit?: boolean): DynamicFormItem[] => {
		const { coupon } = vm.state;
		return [
			{
				type: "text",
				label: "热更新名称",
				name: "versionName",
				required: true,
			},
			{
				type: "select",
				name: "platform",
				label: "更新平台",
				required: true,
				options: updateModelList,
				fieldProps: {
					mode: "multiple",
				},
			},
			{
				type: "custom",
				name: "debug",
				required: true,
				label: "DEBUG版本",
				render: (form: any, record: any) => {
					return (
						<Radio.Group
							options={debugList}
							defaultValue={record.debug}
							onChange={({ target }) => {
								form?.setFieldsValue({ debug: target?.value });
								vm.setState({
									debugMsg: debugList[target?.value].msg,
								});
							}}
						></Radio.Group>
					);
				},
				afterRender: () => {
					return (
						<span
							style={{
								color: "#999",
								fontSize: "12" + "px",
								marginLeft: "155" + "px",
								marginBottom: "10" + "px",
								display: "block",
							}}
						>
							{vm.state.debugMsg}
						</span>
					);
				},
			},
			{
				type: "text",
				label: "热更新版本",
				name: "version",
				required: true,
				afterRender: () => {
					return (
						<span
							style={{
								color: "#999",
								fontSize: "12" + "px",
								marginLeft: "65" + "px",
								marginBottom: "10" + "px",
								display: "block",
							}}
						>
							iOS为Build编译版本号，安卓为versionCode应用版本号。（注：多个版本半角逗号分隔，如：12,13）
						</span>
					);
				},
			},
			{
				type: "text",
				label: "更新包URL",
				name: "fileUrl",
				required: true,
			},
			{
				type: "text",
				label: "包名",
				name: "packages",
				required: true,
			},
			{
				type: "custom",
				name: "valid",
				required: true,
				label: "启用状态",
				render: (form: any, record: any) => {
					return (
						<Radio.Group
							options={enabledStatue}
							defaultValue={record.valid}
							onChange={({ target }) => {
								form?.setFieldsValue({ valid: target?.value });
								vm.setState({
									validMsg: enabledStatue[target?.value].msg,
								});
							}}
						></Radio.Group>
					);
				},
				afterRender: () => {
					return (
						<span
							style={{
								color: "#999",
								fontSize: "12" + "px",
								marginLeft: "155" + "px",
								marginBottom: "10" + "px",
								display: "block",
							}}
						>
							{vm.state.validMsg}
						</span>
					);
				},
			},
			{
				type: "custom",
				name: "updateMode",
				required: true,
				label: "更新模式",
				render: (form: any, record: any) => {
					return (
						<Radio.Group
							options={udateType}
							defaultValue={record.updateMode}
							onChange={({ target }) => {
								form?.setFieldsValue({ updateMode: target?.value });
								vm.setState({
									updateModeMsg: udateType[target?.value].msg,
								});
							}}
						></Radio.Group>
					);
				},
				afterRender: () => {
					return (
						<span
							style={{
								color: "#999",
								fontSize: "12" + "px",
								marginLeft: "155" + "px",
								marginBottom: "10" + "px",
								display: "block",
							}}
						>
							{vm.state.updateModeMsg}
						</span>
					);
				},
			},

			{
				type: "custom",
				name: "clearCache",
				required: true,
				label: "更新完成后-缓存处理",
				render: (form: any, record: any) => {
					return (
						<Radio.Group
							options={updateFinishCache}
							defaultValue={record.clearCache}
							onChange={({ target }) => {
								form?.setFieldsValue({ clearCache: target?.value });
								vm.setState({
									clearCacheMsg: updateFinishCache[target?.value].msg,
								});
							}}
						></Radio.Group>
					);
				},
				afterRender: () => {
					return (
						<span
							style={{
								color: "#999",
								fontSize: "12" + "px",
								marginLeft: "155" + "px",
								marginBottom: "10" + "px",
								display: "block",
							}}
						>
							{vm.state.clearCacheMsg}
						</span>
					);
				},
			},
			{
				type: "custom",
				name: "reboot",
				required: true,
				label: "更新完成后-重启",
				render: (form: any, record: any) => {
					return (
						<Radio.Group
							options={updateFinishRestart}
							defaultValue={record.reboot}
							onChange={({ target }) => {
								form?.setFieldsValue({ reboot: target?.value });
								vm.setState({
									rebootMsg: updateFinishRestart[target?.value].msg,
									isTrue: target.value == "2",
								});
							}}
						></Radio.Group>
					);
				},
				afterRender: () => {
					return (
						<span
							style={{
								color: "#999",
								fontSize: "12" + "px",
								marginLeft: "155" + "px",
								marginBottom: "10" + "px",
								display: "block",
							}}
						>
							{vm.state.rebootMsg}
						</span>
					);
				},
			},
			...(vm.state.isTrue
				? [
						{
							type: "text",
							label: "重启提示标题",
							name: "rebootTitle",
							required: true,
						},
						{
							type: "text",
							label: "重启提示内容",
							name: "rebootMessage",
							required: true,
						},
						{
							type: "custom",
							name: "rebootConfirmReboot",
							label: "点击确定行为",
							required: true,
							render: (form: any, record: any) => {
								return (
									<Radio.Group
										options={handleClick}
										defaultValue={record.rebootConfirmReboot}
										onChange={({ target }) => {
											form?.setFieldsValue({
												rebootConfirmReboot: target?.value,
											});
										}}
									></Radio.Group>
								);
							},
						},
				  ]
				: []),
		];
	};

	// 一体化表格props
	const tablePorps: IntegrationTableProps = {
		rowKey: "id",
		scroll: { x: 1000 },
		columns,
		actionRef,
		listProps: {
			url: "/version/hot-update-list",
			method: "GET",
			requestType: "params",
			paramsHandle: (params: any) => {
				return {
					...params,
				};
			},
		},
		addProps: {
			url: "/version/hot-update-add",
			method: "POST",
			modalProps: {
				width: 700,
				formProps: {
					labelCol: { span: 6 },
				},
				formItemsHandle: (_: any, vm: any) => {
					return getFormItems(vm);
				},
				formValuesHandle: (record: any) => {
					const roleNames = getString(record?.platform).split(",");
					const roleMap = arrayToObject(updateModelList, {
						label: "value",
						value: "label",
					});
					return {
						...record,
						valid: !record.valid ? "0" : record.valid,
						debug: !record.debug ? "0" : record.debug,
						updateMode: !record.updateMode ? "0" : record.updateMode,
						clearCache: !record.clearCache ? "0" : record.clearCache,
						reboot: !record.reboot ? "0" : record.reboot,
						platform: roleNames.map((m) => roleMap[m]).filter(Boolean),
					};
				},
				content: {
					onInit: (vm) => {
						vm.setState({
							debugMsg: "DEBUG版本无法收到此更新包。",
							validMsg: "开启更新，所有用户都会收到此更新。",
							updateModeMsg: "自动触发，APP自动检测更新。",
							rebootMsg:
								"更新完后没有任何提示，更新内容一般在用户下次使用app时生效。",
							clearCacheMsg:
								"更新完后没有任何提示，更新内容一般在用户下次使用app时生效。",
						});
					},
				},
			},
			paramsHandle: async (params: any) => {
				return {
					...params,
					platform: getArray(params.platform).toString(),
					// rebootConfirmReboot: params.reboot == 2 ? "1" : params.reboot,
				};
			},
		},
		handleOperating: () => {
			return [
				{
					type: "modal",
					props: {
						url: "/version/hot-update-edit",
						method: "POST",
						btnText: "编辑",
						modalProps: {
							width: 700,
							formProps: {
								labelCol: { span: 6 },
							},
							title: "编辑",
							formItemsHandle: (_: any, vm: any) => {
								return getFormItems(vm);
							},
							formValuesHandle: ({ platform, ...params }) => {
								return {
									platform: platform.split(","),
									...params,
								};
							},
							content: {
								onInit: (vm) => {
									let result = vm.state?.record;
									vm.setState({
										debugMsg: debugList[result.debug]?.msg,
										validMsg: enabledStatue[result.valid]?.msg,
										updateModeMsg: udateType[result.updateMode]?.msg,
										rebootMsg: updateFinishRestart[result.reboot]?.msg,
										clearCacheMsg: updateFinishCache[result.clearCache]?.msg,
										isTrue: result.reboot == "2",
									});
								},
							},
						},
						paramsHandle: (params: any, record: any) => ({
							...params,
							id: record.id,
							platform: getArray(params.platform).toString(),
						}),
					},
				},
				{
					type: "custom",
					props: {
						btnText: "复制版本号",
						btnClick: (record: any) => {
							if (copy(record.version)) {
								message.success("复制成功!");
							}
						},
					},
				},
			];
		},
	};

	// 初始化加载数据
	useEffect(() => {
		return () => {
			isUnMounted = true;
		};
	}, []);

	return <IntegrationTable {...tablePorps} />;
};

export default HotUpdate;
